package com.tool.weixin.api;

import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.slf4j.Logger;

import com.tool.weixin.util.HttpUtils;

public class SystemApi {
	
	private static final Logger logger = org.slf4j.LoggerFactory.getLogger(SystemApi.class);

	/**获取微信服务器IP地址**/
	private static final String GET_CALLBACK_IP = "https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=ACCESS_TOKEN";
	/**长连接转短链接**/
	private static final String SHORT_URL = "https://api.weixin.qq.com/cgi-bin/shorturl?access_token=ACCESS_TOKEN";
	
	/**
	 * 长连接转短链接
	 * @param url
	 * @return
	 */
	public static String getShortUrl(String url) {
		String json = "{\"action\":\"long2short\",\"long_url\":\""+url+"\"}";
		String requestUrl = SHORT_URL.replace("ACCESS_TOKEN", AccessTokenApi.getAccessToken().getToken());
        JSONObject jsonObject = HttpUtils.httpRequest(requestUrl, "GET", json);
        String result = "";
        if (null != jsonObject) {
            try {
            	result = jsonObject.getString("short_url");
            } catch (Exception e) {
                logger.error("获取JsapiTicket失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
            }
        }
        return result;
	}
	
	/**
	 * 获取微信服务器IP地址
	 * @return
	 */
	public static List<String> getCallbackIp() {
		String requestUrl = GET_CALLBACK_IP.replace("ACCESS_TOKEN", AccessTokenApi.getAccessToken().getToken());
        JSONObject jsonObject = HttpUtils.httpRequest(requestUrl, "GET", null);
        List<String> result = null;
        if (null != jsonObject) {
            try {
            	JSONArray jsonArray = jsonObject.getJSONArray("ip_list");
            	result = new ArrayList<String>(jsonArray.size());
            	for (Object object : jsonArray) {
					result.add(object.toString());
				}
            } catch (Exception e) {
                logger.error("获取JsapiTicket失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
            }
        }
        return result;
	}
	
	
}
